package com.honkentuber;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * TODO(ptucker) Merge this into Servlet? Or at least make it an attribte of
 * Servlet?
 *
 * @author ptucker
 */
public class AppContext {
  public final HttpServletRequest req;
  public final HttpServletResponse resp;
  public final UserService userService;
  public final MyUser user;
  public final String loginUrl;
  public final String logoutUrl;
  public final TimingLogger timingLogger = new TimingLogger();
  public final PersistenceManager persistenceManager;
  public final Database db;

  public AppContext(HttpServletRequest req, HttpServletResponse resp) {
    this.req = req;
    this.resp = resp;
    this.userService = UserServiceFactory.getUserService();
    String requestUri = req.getRequestURI();
    String queryString = req.getQueryString();
    if (queryString != null && queryString.length() > 0) {
      requestUri += '?' + queryString;
    }
    this.loginUrl = userService.createLoginURL(requestUri);
    this.logoutUrl = userService.createLogoutURL(requestUri);

    this.persistenceManager = PMF.get().getPersistenceManager();
    this.db = newDb();
    this.user = db.fetchOrCreateUser(this.userService.getCurrentUser());
    this.timingLogger.recordTiming("start");
  }

  protected Database newDb() {
    return new Database(this.persistenceManager, this.timingLogger);
  }
}
